package friot.service.cloud.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import friot.model.iot.dtos.IotDeviceDto;
import friot.model.iot.entity.IotDevice;
import friot.model.iot.entity.IotModel;
import friot.model.iot.vo.IotDeviceVo;
import friot.service.cloud.mapper.ContactProductModelMapper;
import friot.service.cloud.mapper.IotDeviceMapper;
import friot.utils.constants.AppHttpCodeEnum;
import friot.utils.constants.RedisConstants;
import friot.utils.exception.ServiceException;
import friot.utils.tools.RedisIdWorker;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * (IotDevice)表服务实现类
 *
 * @author makejava
 * @since 2024-03-13 23:04:36
 */
@Service("iotDeviceService")
public class IotDeviceServiceImpl extends ServiceImpl<IotDeviceMapper, IotDevice> implements IotDeviceService {

    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ContactProductModelMapper contactProductModelMapper;

    /**
     * 添加设备
     *
     * @param deviceDto 设备DTO
     */
    @Override
    public void addDevice(IotDeviceDto deviceDto) {
        // 参数校验
        if (StringUtils.isBlank(deviceDto.getNickname()) || deviceDto.getProductId() == null) {
            throw new ServiceException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 查询产品原型，组装modelKey
        List<IotModel> modelList = contactProductModelMapper.listBindModels(deviceDto.getProductId());
        if (modelList == null || modelList.isEmpty()) {
            throw new ServiceException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        StringBuilder builder = new StringBuilder("{ ");
        for (IotModel model : modelList) {
            builder.append(model.getIdentified())
                    .append(": data, ");
        }
        builder.deleteCharAt(builder.length() - 2);
        builder.append(" }");

        // 保存设备
        IotDevice iotDevice = new IotDevice();
        iotDevice.setDeviceId(redisIdWorker.nextId(RedisConstants.INCR_DEVICE_ID));
        iotDevice.setNickname(deviceDto.getNickname());
        iotDevice.setUserId(2);
        iotDevice.setModelId(deviceDto.getProductId());
        iotDevice.setModelKey(builder.toString());
        save(iotDevice);

        // 将设备ID加入Redis
        stringRedisTemplate.opsForSet()
                .add(RedisConstants.CLOUD_DEVICE_IDS, String.valueOf(iotDevice.getDeviceId()));
    }

    /**
     * 查询所有设备
     *
     * @return 设备列表VO
     */
    @Override
    public List<IotDeviceVo> listAndMapByUserId(Integer userId) {
        List<IotDevice> list = lambdaQuery().eq(IotDevice::getUserId, userId).list();
        List<IotDeviceVo> iotDeviceVoList = new ArrayList<>();
        for (IotDevice iotDevice : list) {
            IotDeviceVo iotDeviceVo = new IotDeviceVo();
            BeanUtil.copyProperties(iotDevice, iotDeviceVo, "deviceId");
            iotDeviceVo.setDeviceId(String.valueOf(iotDevice.getDeviceId()));
            iotDeviceVoList.add(iotDeviceVo);
        }
        return iotDeviceVoList;
    }
}

